const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const log4js = require('./utils/log4j')
const router = require("koa-router")()
const jwt = require("jsonwebtoken")
const koajwt = require("koa-jwt")
const utils = require('./utils/utils')

const cors = require('koa2-cors');



const users = require('./routes/users')
const menus = require('./routes/menus')
const roles = require('./routes/roles')
const depts = require('./routes/depts')
const leaves = require('./routes/leaves')
// error handler
app.use(cors());//允许跨域
onerror(app)
require("./config/db")

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())


// app.use(logger())

// const logger = log4js.getLogger();
// logger.level = "debug";
// logger.debug("xixixix ")

app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  log4js.info(`get params:${JSON.stringify(ctx.request.query)}`);
  log4js.info(`post params:${JSON.stringify(ctx.request.body)}`);
  const start = new Date()
  await next().catch((err) => {
    if (err.status == '401') {
      ctx.status = 200;
      ctx.body = utils.fail("Token 验证失败", utils.CODE.AUTH_ERROR)
    } else {
      throw err;
    }
  })
  // const ms = new Date() - start
  // console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

app.use(koajwt({ secret: "wmm" }).unless({
  path: [/^\/api\/users\/login/]
}))
router.prefix("/api");
router.get("/leave/count", (ctx) => {
  // 拿到前端携带过来的token进行验证 
  const token = ctx.request.headers.authorization.split(" ")[1];
  const payload = jwt.verify(token, "wmm");
  // ctx.body = payload;
  ctx.body = utils.success(payload)
})

router.use(users.routes(), users.allowedMethods())
router.use(menus.routes(), users.allowedMethods())
router.use(roles.routes(), users.allowedMethods())
router.use(depts.routes(), depts.allowedMethods())
router.use(leaves.routes(), leaves.allowedMethods())
app.use(router.routes(), router.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  // console.error('server error', err, ctx)
  log4js.error(err.stack);
});

module.exports = app
